package 手写线程池;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * @author chedx
 * @data 2021/3/20 10:31 PM
 */
public class ThreadPool {
    /***
     * 1.阻塞队列
     */
    BlockingQueue<Runnable> workQueue ;

    /***
     *   / 2.保存内部工作线程
     */
    List<WorkThread> workThreadList = new ArrayList<>();

    public ThreadPool(int poolsize, BlockingQueue<Runnable> workQueue) {
        this.workQueue = workQueue;
        for (int i = 0; i < poolsize; i++) {
            WorkThread workThread = new WorkThread();
            workThread.start();
            workThreadList.add(workThread);
        }
    }

    /***
     * 执行方法
     * @param runnable
     * @throws Exception
     */
    void execute(Runnable runnable) throws Exception{
        workQueue.put(runnable);
    }

    /***
     * 内部工作线程
     */
    public  class WorkThread extends Thread {
        @Override
        public void run() {
            while (true) {
                Runnable task = null;
                try {
                    task = workQueue.take();
                    task.run();
                }catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
